package dao

import (
	"context"
	"mini-app/internal/models"
	"time"

	"192.168.1.75/go-pkg/errorx"
	"gorm.io/gorm"
)

type Announcement struct{}

func (Announcement) Create(
	ctx context.Context,
	db *gorm.DB,
	record models.Announcement,
) (id string, err error) {
	rowsAffected := db.WithContext(ctx).Model(&models.Announcement{}).Create(&record).RowsAffected
	if rowsAffected <= 0 {
		return "", errorx.New("新增公告失败", -1)
	}
	return record.ID, nil
}
func (Announcement) Update(
	ctx context.Context,
	db gorm.DB,
	id, name, content string,
	startTime, endTime int64,
) error {
	return db.WithContext(ctx).Model(&models.Announcement{}).
		Where("id = ?", id).
		Updates(&models.Announcement{
			Name:      name,
			Content:   content,
			StartTime: startTime,
			EndTime:   endTime,
		}).Error
}
func (Announcement) Delete(
	ctx context.Context,
	db *gorm.DB,
	id string,
) bool {
	rowsAffected := db.WithContext(ctx).Model(&models.Announcement{}).
		Where("id = ?", id).
		Delete(&models.Announcement{}).
		RowsAffected
	return rowsAffected == 1
}

func (Announcement) Detail(
	ctx context.Context,
	db *gorm.DB,
	id string,
) *models.Announcement {
	var record models.Announcement
	rowsAffected := db.WithContext(ctx).Model(&models.Announcement{}).
		Where("id = ?", id).
		Take(&record).
		RowsAffected
	if rowsAffected <= 0 {
		return nil
	}
	return &record
}

func (Announcement) List(
	ctx context.Context,
	db *gorm.DB,
	name string,
	status int, // 1-进行中 2-未开始 3-已结束
	page, limit int,
) (records []models.Announcement, total int64) {
	tx := db.WithContext(ctx).Model(&models.Announcement{})
	if name != "" {
		tx = tx.Where("name LIKE ?", "%"+name+"%")
	}
	newTs := time.Now().Unix()
	switch status {
	case 1: // 未开始
		tx = tx.Where("start_time > ?", newTs)
	case 2: // 进行中
		tx = tx.Where("start_time <= ? AND end_time >= ?", newTs, newTs)
	case 3:
		tx = tx.Where("end_time < ?", newTs)
	}
	tx.Count(&total)
	if limit > 0 {
		if limit > 2000 {
			limit = 2000
		}
		tx = tx.Limit(limit)
	}
	if page > 0 && limit > 0 {
		tx = tx.Offset((page - 1) * limit)
	}
	tx.Order("created_at desc").Find(&records)
	if len(records) == 0 {
		records = []models.Announcement{}
	}
	return
}
